package cn.com.netedge.iot.frontend.biz.service.impl;

import com.alibaba.fastjson2.JSON;
import cn.com.netedge.iot.common.constants.CacheKeyConstants;
import cn.com.netedge.iot.common.constants.Globals;
import cn.com.netedge.iot.common.dataobject.DeviceInfo;
import cn.com.netedge.iot.common.utils.RedisUtil;
import cn.com.netedge.iot.common.utils.StringUtil;
import cn.com.netedge.iot.frontend.biz.dao.AchvDcuMapper;
import cn.com.netedge.iot.frontend.biz.dao.AchvMeterMapper;
import cn.com.netedge.iot.frontend.biz.service.DeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class DeviceServiceImpl implements DeviceService {
    private static final String KEY_EXIST_ARCHIVE = "exist_archive_"; // + deviceNumber_deviceType
    private static final String BOOLEAN_TRUE = "true";
    private static final int DEVICE_TYPE_METER = 0;
    private static final int DEVICE_TYPE_UNKNOWN = -1;

    @Autowired
    private AchvDcuMapper achvDcuMapper;
    @Autowired
    private AchvMeterMapper achvMeterMapper;

    @Override
    public DeviceInfo getDeviceInfo(String deviceNumber, int deviceType) {
        String key = CacheKeyConstants.KEY_DEVICE_INFO + deviceNumber + "_" + deviceType;
        String value = RedisUtil.get(key);
        if (StringUtil.isNotEmpty(value) && BOOLEAN_TRUE.equalsIgnoreCase(value)) {
            return JSON.parseObject(value, DeviceInfo.class);
        }
        Short protocol = null;
        if(DEVICE_TYPE_UNKNOWN == deviceType) {
            protocol = achvMeterMapper.selectMeterProtocol(deviceNumber);
            if(protocol == null) {
                protocol = achvDcuMapper.selectDcuProtocol(deviceNumber);
            }
        } else if (DEVICE_TYPE_METER == deviceType) {
            protocol = achvMeterMapper.selectMeterProtocol(deviceNumber);
        } else {
            protocol = achvDcuMapper.selectDcuProtocol(deviceNumber);
        }
        if (protocol != null) {
            DeviceInfo deviceInfo = new DeviceInfo();
            deviceInfo.setDeviceNumber(deviceNumber);
            deviceInfo.setDeviceType(deviceType);
            deviceInfo.setProtocol(protocol);
            RedisUtil.set(key, JSON.toJSONString(deviceInfo), Globals.DEFAULT_CACHE_EXPIRE_TIME, TimeUnit.SECONDS);
            return deviceInfo;
        }
        return null;
    }
}
